#from CannyEdge.utils import to_ndarray
#from CannyEdge.core import (gs_filter, gradient_intensity, suppression,
                         #   threshold, tracking)

import cv2
import numpy as np
from PIL import Image
#from scipy import misc


img = cv2.imread('xinza.jpg')

'''改变图像大小'''
# size = img.shape
# img_resize = cv2.resize(img, (size[1]/2, size[0]/2), cv2.INTER_LINEAR)
# img_resize = cv2.resize(img, (1289, 720), cv2.INTER_LINEAR)
img_resize = cv2.resize(img, (480, 720), cv2.INTER_CUBIC)
im =img_resize.copy()

'''预览图像'''
def look_image(image):
    # cv2.namedWindow('lab325_xinza', cv2.WINDOW_NORMAL)
    cv2.namedWindow('lab325_xinza')
    # cv2.resizeWindow('lab325_xinza', 1000, 1000)
    cv2.imshow('lab325_xinza', img_resize)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    # cv2.namedWindow('Image')

    '''平滑'''
def blur_demo(image):
    # gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) #如果执行直方图均衡化，就不要这步操作
    # blurred_1 = cv2.GaussianBlur(image, (11,11), 0)  # 低通高斯滤波 平滑处理
    blurred_2 = cv2.bilateralFilter(src=image, d=0, sigmaColor=100, sigmaSpace=15)  # 低通效果不错 参数如何调整
    # blurred_2 = image - blurred_1
    # cv2.imshow('blurred_1',blurred_2) #预览效果作用
    return blurred_2

    '''锐化'''
def custom_blur_demo(image):
    kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]], np.float32)  # 锐化
    dst = cv2.filter2D(image, -1, kernel=kernel)
    # cv2.imshow("custom_blur_demo", dst) #预览效果作用
    return dst

    '''亮度和对比度调节'''
def Contrast_and_Brightness(alpha, beta, img):
    blank = np.zeros(img.shape, img.dtype)
    # dst = alpha * img + beta * blank
    dst = cv2.addWeighted(img, alpha, blank, 1 - alpha, beta)
    # cv2.imshow('constrast', dst) #预览效果作用
    return dst


##cv2.namedWindow('325_input_image')   #预备预览图像作用
##cv2.imshow('325_input_image', img_resize)

'''type_1'''
'''平滑和对比度结合处理'''
# 效果来看 模糊很厉害
# img_blur = blur_demo(img_resize)
# custom_blur_demo(img_resize)
# Contrast_and_Brightness(1.2,1,img_blur)
# img_blur = blur_demo(img_resize)

'''type_2'''
'''平滑和锐化结合'''
'''
img_blur = blur_demo(img_resize)
custom_blur_demo(img_blur)
'''

'''type3'''
'''三者结合'''
'''
img_blur = blur_demo(img_resize)
dst =custom_blur_demo(img_blur)
Contrast_and_Brightness(1.2,1,dst)
'''

# cv2.waitKey(0)
# cv2.destroyAllWindows()  #预览效果作用

'''绘制直方图观察颜色分布'''
from matplotlib import pyplot as plt


def hist_img(image):
    wiki_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    hist, bins = np.histogram(wiki_img.ravel(), bins=10)
    # print(hist)
    # print(bins)
    plt.hist(wiki_img.ravel(), bins=50)
    plt.show()
    equ_wiki_img = cv2.equalizeHist(wiki_img)
    plt.hist(equ_wiki_img.ravel(), bins=50)
    plt.show()
    return equ_wiki_img


# equ_wiki_img = hist_img(img_resize)
# cv2.imshow('equ_wiki_img', equ_wiki_img) #显示均衡化的图 让图片层次更加分明
# cv2.waitKey(0)
# cv2.destroyAllWindows()

'''type4'''
'''暂时觉得直方图均衡后，在用双边平滑滤波后效果较好'''
#######Contrast = Contrast_and_Brightness(1.2,1,equ_wiki_img)
'''type4_1'''  ###############这种暂时觉得很好
equ_wiki_img = hist_img(img_resize)
img_blur = blur_demo(equ_wiki_img)

'''type4_2'''
# img_blur = blur_demo(img_resize)
# equ_wiki_img = hist_img(img_blur)

# custom_blur_demo(img_blur)

#cv2.waitKey(0)
#cv2.destroyAllWindows()  # 预览效果作用
############img = cv2.threshold(img_blur, 0, 255,cv2.THRESH_OTSU)[1]

# img = cv2.threshold(img_blur, 100, 255,cv2.THRESH_BINARY)[1] #暂时感觉不错#这里面参数不同带来
img2 = cv2.threshold(img_blur, 100, 255, cv2.THRESH_BINARY_INV)[1]
# 键盘检测函数，0xFF是因为64位机器
# https: // stackoverflow.com / questions / 20539497 / opencv - python - waitkey d- dont - respond

'''两种情况对比来看，所以没有把部分代码注释'''
# 闭运算
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))

# opening = cv2.morphologyEx(img2, cv2.MORPH_OPEN, kernel)
# closing = cv2.morphologyEx(img2, cv2.MORPH_CLOSE, kernel)

# cv2.imshow("Image", opening)
# cv2.imshow('Image2', closing)

'''自定义形态学'''  # 从画线来看这样操作更合适
img2 = cv2.erode(img2, kernel, iterations=2)  # 参数2或者3都区别不大
img2 = cv2.dilate(img2, kernel, iterations=3)
##img = cv2.erode(img2, kernel, iterations=2)
##img = cv2.dilate(img2, kernel, iterations=3)

# cv2.imshow('image3',img)
# cv2.waitKey(0)

# cv2.destroyAllWindows()

'''轮廓'''
image, contours, hierarchy = cv2.findContours(img2.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img_resize, contours, -1, (0, 0, 255), 2)

img1 = Image.fromarray(im)
img3 = Image.fromarray(img2)
cv2.imwrite('yuan.jpg',im)
cv2.imwrite('xin.jpg',img2)
plt.subplot(2, 2, 1), plt.imshow(im, cmap='gray'),plt.xticks([]), plt.yticks([])
plt.subplot(2, 2, 2), plt.imshow(img_blur, cmap='gray'),plt.xticks([]), plt.yticks([])
plt.subplot(2, 2, 3), plt.imshow(img2, cmap='gray'),plt.xticks([]), plt.yticks([])
plt.subplot(2, 2, 4), plt.imshow(img_resize, cmap='gray'),plt.xticks([]), plt.yticks([])


plt.show()

# cnts = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# cnts = cnts[0]


'''掩模'''
# mask = np.zeros(img_resize.shape).astype(img_resize.dtype)
#
# color = [255, 255, 255]
#
# cv2.fillPoly(mask, cnts, color)
#
# result = cv2.bitwise_and(img_resize, mask)
#
# cv2.imwrite("result.jpg", result)
